package com.gkoudai.open.platform;

import com.gkoudai.open.platform.client.HttpRequestClient;
import com.gkoudai.open.platform.client.SocketIoClient;
import com.gkoudai.open.platform.entry.Property;
import com.gkoudai.open.platform.handler.DataHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;

/**
 * @author : Amater
 * @date : 2024/10/28 16:49
 */
@Slf4j
@EnableConfigurationProperties({Property.class})
public class OpenPlatformSocketAutoConfiguration implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    @Bean
    public SocketIoClient socketIoClient(Property property) {
        DataHandler bean = null;
        try {
            if (applicationContext != null) {
                bean = applicationContext.getBean(DataHandler.class);
            }
        } catch (Exception e) {
            log.warn("com.gkoudai.open.platform.handler.DataHandler not  exist in spring");
        }
        if (Boolean.TRUE.equals(property.getEnableSocket())) {
            SocketIoClient socketIoClient = new SocketIoClient(property, bean);
            if (Boolean.TRUE.equals(property.getEnableQuote())) {
                socketIoClient.subscribeQuote();
                socketIoClient.subscribeStockQuote();
            }
            if (Boolean.TRUE.equals(property.getEnableNews())) {
                socketIoClient.subscribeNews();
            }
            if (Boolean.TRUE.equals(property.getEnableFuturesQuote())){
                socketIoClient.subscribeNewFuturesQuote();
            }

            return socketIoClient;
        }
        return null;

    }

    @Bean
    public HttpRequestClient httpRequestClient(Property property) {
        return new HttpRequestClient(property);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
